package com.topvision.opencv_test;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;
import android.view.WindowManager;

import org.opencv.core.Rect;

/**
 * Author: lucy
 * Comment: //TODO
 * Date: 2017-10-11 11:13
 */

public class DrawRectView extends View {
    private boolean needDrawRect;
    private boolean needClearRect;
    private Paint mPaint;
    private int mStartX;
    private int mStartY;
    private int mRectHeight;
    private int mRectWidth;
    private int mScreenHeight;
    private int mScreenWidth;

    public DrawRectView(Context context) {
        super(context);
        init();
    }

    public DrawRectView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public DrawRectView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        mScreenHeight = windowManager.getDefaultDisplay().getHeight();
        mScreenWidth = windowManager.getDefaultDisplay().getWidth();
        initPaint();
    }

    private void initPaint() {
        mPaint = new Paint();
        mPaint.setColor(Color.RED);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(5);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (needDrawRect) {
            mHandler.removeCallbacksAndMessages(null);
            canvas.drawRect(mStartX, mStartY, mStartX + mRectWidth, mStartY + mRectHeight, mPaint);
            mHandler.sendEmptyMessageDelayed(CLEAR, 150);
            needDrawRect = false;
        } else if (needClearRect){
            needClearRect = false;
            canvas.drawColor(Color.TRANSPARENT);
        }
    }

    public void drawRect(Rect rect) {
        needDrawRect = true;
        mStartX = rect.x;
        mStartY = rect.y;
        mRectHeight = rect.height;
        mRectWidth = rect.width;
        System.out.println("X：" + mStartX + ", Y：" + mStartY+", Width："+mRectWidth+", Height："+mRectHeight);
        invalidate();
    }

    public void clearDraw() {
        needClearRect = true;
        invalidate();
    }

    public static final int CLEAR = 0;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CLEAR:
                    clearDraw();
                    break;
            }
        }
    };
}
